<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\model;


use think\Queue;
use Think\Db;

/**
 * Game模型
 */
class ThirdPlanUserProgramme extends ModelBase
{

    protected $insert = ['create_time'];




    /**
     * 时间自动完成
     */
    public function setCreateTimeAttr()
    {

        return TIME_NOW;
    }



    /**
     * 自动挂机
     */

    public function plan_auto(){

        //当前期数
        $round=LotteryRound::where(['lottery_id'=>$this->lottery_id,'state'=>2])->value('round');

        if($round){
            if($this->is_simulation==1){
                $info=BetsLogSubscribe::where(['round'=>$round,'user_id'=>$this->user_id,'lottery_id'=>$this->lottery_id])->find();
                if($info){
                    return 0;
                }
                //模拟下注
                //当前期数同步下注
                $arr = array(
                    'user_id'=>$this->user_id,
                    'lottery_id'=>$this->lottery_id,
                    'play_id'=>$this->play_id,
                    'round'=>$round,
                    'number'=>$this->number,
                    'injection_number'=>$this->injection_number,
                    'mult'=>$this->mult,
                    'has_round'=>$this->current_round+1,
                    'univalent'=>$this->univalent,
                    'state'=>1,//1待开奖  2中奖 3:未中
                    'money'=>$this->round_money,   //本金
                    'create_time'=>TIME_NOW,
                    'odds'=>$this->play->mult,
                    'point_odds'=>0,
                    'return_point_money'=>0,
                    'is_old'=>$this->play->is_old,
                    'programme_id'=>$this->id,

                );
                $mult=$this->doubule->get_mult($this->current_times);
                if($mult>0){
                    $arr['mult']=$mult;
                }

                $arr['money']=$this->injection_number*$this->univalent*$arr['mult'];
                BetsLogSubscribe::create($arr);

            }else{
                $info=BetsLog::where(['round'=>$round,'user_id'=>$this->user_id,'lottery_id'=>$this->lottery_id,'entrust_count'=>0])->find();
                if($info){
                    return 0;
                }
                //真实下注
                // 1.当前任务将由哪个类来负责处理。
                //   当轮到该任务时，系统将生成一个该类的实例，并调用其 fire 方法
                $jobHandlerClassName  = 'app\api\job\Consumer';
                $king_id=$this->king_id;
                // 2.当前任务归属的队列名称，如果为新队列，会自动创建
                $jobQueueName  	  = "ConsumerJobQueue";
                $arr = array(
                    'user_id'=>$this->user_id,
                    'lottery_id'=>$this->lottery_id,
                    'play_id'=>$this->play_id,
                    'round'=>$round,
                    'number'=>$this->number,
                    'injection_number'=>$this->injection_number,
                    'user_investment_id'=>$this->user_investment_id,
                    'king_id'=>$king_id,
                    'mult'=>$this->mult,
                    'has_round'=>$this->current_round+1,
                    'univalent'=>$this->univalent,
                    'entrust_count'=>0,
                    'state'=>1,//1待开奖  2中奖 3:未中
                    'money'=>$this->round_money,   //本金
                    'create_time'=>TIME_NOW,
                    'odds'=>$this->play->mult,
                    'point_odds'=>0,
                    'return_point_money'=>0,
                    'is_old'=>$this->play->is_old,
                    'programme_id'=>$this->id,
                    'trade_no'=>'BT'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999),

                );
                $mult=$this->doubule->get_mult($this->current_times);
                if($mult>0){
                    $arr['mult']=$mult;
                }
                $arr['money']=$this->injection_number*$this->univalent*$arr['mult'];
                $game=[
                    'user_id'=>$this->user_id,
                    'king_id'=>0,
                    'user_investment_id'=>$this->user_investment_id,
                    'investment_id'=>0,
                    'type'=>4,
                    'entrust_count'=>0,
                    'state'=>3,
                    'order_no'=>$arr['trade_no'],
                    'number'=> $arr['money'],
                    'create_time'=>TIME_NOW,
                    'users'=>''

                ];


                if($this->user_investment_id>0){
                    $investment=GamblerKingInvestmentUser::get($this->user_investment_id);
                    if($investment['state']==5 || $investment['state']==6){
                        //结束挂机
                        $this->state=4;
                        $this->has_end_time=TIME_NOW;
                        $this->save();
                        return 1;
                    }
                    $order_count=$investment->order_count;
                    $money=$arr['money']*$order_count;
                    $king=GamblerKing::get($this->king_id);
                    if($king['balance']<$arr['money']){
                        //余额不足停止挂机
                        $this->state=3;
                        $this->save();
                        return 2;
                    }
                    if($king['king_win_account']<$money){
                        //余额不足停止挂机
                        $this->state=3;
                        $this->save();
                        return 3;
                    }


                    $arr_two = array(
                        'user_id'=>$this->user_id,
                        'lottery_id'=>$this->lottery_id,
                        'play_id'=>$this->play_id,
                        'round'=>$round,
                        'number'=>$this->number,
                        'injection_number'=>$this->injection_number,
                        'user_investment_id'=>$this->user_investment_id,
                        'king_id'=>$king_id,
                        'mult'=>$arr['mult']*$order_count,
                        'has_round'=>$this->current_round+1,
                        'univalent'=>$this->univalent,
                        'entrust_count'=>0,
                        'state'=>1,//1待开奖  2中奖 3:未中
                        'money'=>$money,   //本金
                        'create_time'=>TIME_NOW,
                        'odds'=>$this->play->mult,
                        'point_odds'=>0,
                        'return_point_money'=>0,
                        'is_old'=>$this->play->is_old,
                        'programme_id'=>$this->id,
                        'trade_no'=>'BT'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999),

                    );
                    $game_two=[
                        'user_id'=>$this->user_id,
                        'king_id'=>0,
                        'user_investment_id'=>0,
                        'investment_id'=>$investment['investment_id'],
                        'type'=>4,
                        'entrust_count'=>$order_count,
                        'state'=>3,
                        'order_no'=>$arr_two['trade_no'],
                        'number'=> $arr_two['money'],
                        'create_time'=>TIME_NOW,
                        'users'=>''

                    ];
                    $userids=UserKingInvestment::where(['user_investment_id'=>$this->user_investment_id,'state'=>6])->column('user_id');
                    if($userids){
                        foreach ($userids as $k=>$v){
                            $investment_bet_log=[
                                'create_time'=>TIME_NOW,
                                'user_investment_id'=>$this->user_investment_id,
                                'user_id'=>$v,
                                'trade_no'=>$arr_two['trade_no'],
                                'number'=>$arr_two['money']
                            ];
                            $investment_bet_logs[]=$investment_bet_log;
                        }
                        $userids=','.implode(',',$userids).',';

                    }else{
                        $investment_bet_logs=[];
                        $userids='';
                    }
                    if(!empty($investment_bet_logs)){
                        Db::name('investment_bet_log')->insertAll($investment_bet_logs);
                    }
                    $game['investment_id']=$investment['investment_id'];
                    $game_two['users']=$userids;
                    $arrs[]=$arr;
                    $games[]=$game;
                    $arrs[]=$arr_two;
                    $games[]=$game_two;
                    //委托挂机下注

                    Db::name('games_log')->insertAll($games);
                    Db::name('bets_log')->insertAll($arrs);
                    Queue::push($jobHandlerClassName,$arr['trade_no'], $jobQueueName);
                    Queue::push($jobHandlerClassName,$arr_two['trade_no'], $jobQueueName);

                }else{
                    //用户挂机

                    //赌王下注

                    $user_account=UserAccount::check(['user_id'=>$this->user_id,'wallet_id'=>1],false);

                    if($user_account['balance']<$arr['money']){
                        //余额不足停止挂机
                        $this->state=3;
                        $this->save();
                        return 0;
                    }else{

                        //扣除余额
                        $user_account->balance-=$arr['money'];
                        $user_account->save();

                        //写入流水
                        UserAccountLog::create([
                            'user_id'=>$this->user_id,
                            'wallet_id'=>1,
                            'before_blance'=>$user_account->balance+$arr['money'],
                            'after_blance'=>$user_account->balance,
                            'remark'=>'挂机下注'.$this->lottery->data['name'].$round.'期',
                            'number'=>$arr['money'],
                            'type'=>29,
                            'is_add'=>2,
                        ]);
                        Db::name('games_log')->insert($game);
                        Db::name('bets_log')->insert($arr);
                       Queue::push($jobHandlerClassName,$arr['trade_no'], $jobQueueName);

                    }


                }



            }
            PlanProgramme::where(['id'=>$this->programme_id])->setInc('bets_count',1);
            //当前期数+1
            $this->bets_money+=$arr['money'];
            $this->current_round+=1;
            $this->save();
            return 8;
        }



    }


    /**
     * 连彩种表
     */
    public function lottery(){
        return $this->belongsTo('Lottery','lottery_id','id');
    }

    /**
     * 连玩法表
     */
    public function play(){
        return $this->belongsTo('LotteryPlay','play_id','id');
    }
    /**
     * 连号码组表
     */
    public function bets(){
        return $this->belongsTo('PlanUserNumber','number_id','id');
    }
    /**
     * 连倍投表
     */
    public function doubule(){
        return $this->belongsTo('PlanUserThrow','throw_id','id');
    }
    /**
     * 连倍投表
     */
    public function programme(){
        return $this->belongsTo('PlanProgramme','programme_id','id');
    }


   



}
